package com.jt.mapper;

import com.jt.exception.ServiceException;
import com.jt.pojo.SearchItem;
import com.jt.pojo.SearchResult;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author dc
 * @Classname SearchMapper
 * @Date 2020/5/28 15:33
 */
@Component
public class SearchMapper {
    /**
     * SolrClient实例是在 SolrAutoConfiguration 类中创建的
     * SolrAutoConfiguration添加了@Configuration注解,
     * 是spring boot自动配置类,其中的solrClient()方法中创建了SolrClient实例
     **/
    @Autowired
    private SolrClient solrClient;

    public SearchResult search(SolrQuery query) {
        try {
            SearchResult result=new SearchResult();
            //获取查询响应结果
            QueryResponse queryResponse=solrClient.query(query);
            //获取查询的文档列表
            SolrDocumentList documentList = queryResponse.getResults();
            //取查询总数量并注入返回结果中
            result.setRecordCount(documentList.getNumFound());
            Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
            List<SearchItem> itemList=new ArrayList<>();
            //循环设置对象
            for(SolrDocument solrDocument:documentList){
                SearchItem item=new SearchItem();
                item.setId((String) solrDocument.get("id"));
                item.setImage((String) solrDocument.get("image"));
                item.setSellPoint((String) solrDocument.get("sellPoint"));
                item.setPrice((Long) solrDocument.get("price"));
                //solrDocument.get("id")获取id值，highlighting.get("id")，k为id，v为title
                List<String> titleList = highlighting.get(solrDocument.get("id")).get("title");
                if(titleList.size()>0&&titleList!=null){
                    item.setTitle(titleList.get(0));
                }else{
                    throw new ServiceException("标题搜索失败");
                }
                itemList.add(item);
            }
            result.setItemList(itemList);
            return result;
        } catch (SolrServerException e) {
            e.printStackTrace();
            throw new ServiceException("搜索服务繁忙,请稍后再试");
        } catch (IOException e) {
            e.printStackTrace();
            throw new ServiceException("当前网络繁忙,请稍后再试");
        }
    }
}
